package psd.model.Prolog;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import jpl.Atom;
import jpl.JPL;
import jpl.PrologException;
import jpl.Query;
import jpl.Term;
import psd.config.ConfigurationReader;
import psd.model.Bug;


public class JPLQueryExecuter implements PrologQueryExecuter{
	
	public JPLQueryExecuter()
	{
		JPL.init();
		String database = ConfigurationReader.Instance().getProperty(
				"databasePath")
				+ "\\PSD.pl";
		Query query = null;
		try {
			query = new Query("consult", new Term[] { new Atom(database) });
			if (!query.query()) {
				 System.out.println("consult PSD failed");
				 }
		} catch (PrologException e) {
			System.out.println(e.getMessage());
		} finally {
			if(query != null){
			query.rewind();
			query.close();
			}
		}
	}
	
//	public static void LoadMetaModel() {
//	
//	}
	
	public List<Bug> executeQuery(PrologRule rule)
	{
		List<Bug> returnList = new ArrayList<Bug>();
		String lineNumber= null;
		String filePath= null;
		Bug bug = null;
		try
		{
		
		Hashtable[] table =  new Query(rule.getQuery()).allSolutions();
		for(int i = 0; i < table.length; i++)
		{
			lineNumber = table[i].get("LN").toString();
			filePath = table[i].get("PATH").toString();
			bug = new Bug();
			
			bug.set_ruleName(rule.getName());
			bug.set_ruleid(rule.getId());
			bug.set_description(rule.getDescription());
			bug.set_lineNumber(Integer.parseInt(lineNumber));
			bug.set_path(filePath.toString());
			bug.set_priority(rule.getPriority());
			returnList.add(bug);
		}
		
		}
		catch(PrologException e)
		{
			System.out.println(e.getMessage());
		}
		
		return returnList;
	}

}
